package com.malex.mxtracker.storage;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author Manusovich Alexander
 */
public class DatabaseManager extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String OPERATIONS_TABLE_CREATE =
            "CREATE TABLE operation (_id integer primary key autoincrement, "
                    + "value DOUBLE, type BYTE, description TEXT);";
    private SQLiteDatabase db;


    public DatabaseManager(Context context) {
        super(context, "mxtracker", null, DATABASE_VERSION);
        this.db = getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(OPERATIONS_TABLE_CREATE);
    }

    @Override
    public void onUpgrade(final SQLiteDatabase sqLiteDatabase,
                          final int oldVersion, final int newVersion) {
        Log.w(getClass().getSimpleName(), "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS operation");
        onCreate(sqLiteDatabase);
    }

    public void addIncoming() {
        ContentValues initialValues = new ContentValues();
        initialValues.put("description", "ag " + Math.random());
        initialValues.put("type", 1);
        initialValues.put("value", Math.random());
        getDb().insert("operation", null, initialValues);
    }

    public Cursor fetchAllNotes() {
        return getDb().query("operation",
                new String[]{"_id", "value"}, null, null, null, null, null);
    }

    public SQLiteDatabase getDb() {
        return db;
    }
}
